import eventBus from "@/eventBus";
import {debounce} from "@/utils";
import defaultGif from "@/assets/default.gif";

//存放所有imgs
const imgs = [];
window.imgs = imgs;

function save(item) { //如果保存过的
    imgs.push(item)
}

function deleteHandle(el) {
    const deleteIndex = imgs.findIndex(it => it.dom === el);
    imgs.splice(deleteIndex, 1);
}


// 监听滚动条
const handleScrollDebounce = debounce(handleScroll);
eventBus.$on('mainScroll',handleScrollDebounce)

//监听视口变化
window.addEventListener("resize", ()=>{
    showCurrentImg();
});

function handleScroll(){
    showCurrentImg();
}


// 显示正确的img
function showCurrentImg() {
    if(imgs.length == 0) return;
    for (const item of imgs) {
        const dom = item.dom;
        const rect = dom.getBoundingClientRect();
        const Height  = rect.height || 150;   //由于刚v-bind的时候还没有图片加载，所以高度是为0
        const Top = rect.top;
        if (Top < -Height || Top > document.documentElement.clientHeight) { //在视口的上方 或 下方
            continue;
        } else if (!item.isShow) { // 在视口的范围里面并且没有show过的
            item.isShow = true;
            const tempImg = new Image();
            tempImg.onload = function() {
              // 当真实图片加载完成之后
              item.dom.src = item.src;     // 加载完成的图片会有缓存
            };
            tempImg.src = item.src;
        }
    }
}


export default {
    inserted(el, bindings) {
        el.src = defaultGif;
        save({
            dom: el,
            src: bindings.value,
            isShow: false,
        });
        //立即判断一下是否在视口内
        showCurrentImg()
    },

    unbind(el) { //解绑是要把img给delete
        deleteHandle(el)
    }
}